import { College } from '../mock/collegeData';

// 学院管理服务接口
export interface ICollegeService {
  getColleges(): Promise<College[]>;
  getCollege(id: number): Promise<College | undefined>;
  addCollege(college: Omit<College, 'id' | 'createdAt' | 'updatedAt'>): Promise<College>;
  updateCollege(id: number, college: Partial<College>): Promise<College | undefined>;
  deleteCollege(id: number): Promise<boolean>;
  searchColleges(query: string): Promise<College[]>;
}

// 学院管理服务实现类
export class CollegeService implements ICollegeService {
  private readonly STORAGE_KEY = 'colleges';
  private colleges: College[] = [];
  private isInitialized = false;

  // 初始化数据
  private async initialize(): Promise<void> {
    if (this.isInitialized) return;
    
    try {
      // 尝试从localStorage获取数据
      const savedColleges = localStorage.getItem(this.STORAGE_KEY);
      if (savedColleges) {
        this.colleges = JSON.parse(savedColleges);
      } else {
        // 从mock导入初始数据
        const { mockColleges } = await import('../mock/collegeData');
        this.colleges = [...mockColleges];
        this.saveToStorage();
      }
    } catch (error) {
      console.error('初始化学院数据失败:', error);
      throw new Error('初始化学院数据失败');
    }
    
    this.isInitialized = true;
  }

  // 保存到localStorage
  private saveToStorage(): void {
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.colleges));
    // 通知仪表盘数据更新
    try {
      const { dashboardDataManager } = require('../mock/collegeData');
      dashboardDataManager.notifyListeners();
    } catch (error) {
      console.warn('通知数据更新失败:', error);
    }
  }

  // 获取所有学院
  async getColleges(): Promise<College[]> {
    await this.initialize();
    return [...this.colleges];
  }

  // 获取单个学院
  async getCollege(id: number): Promise<College | undefined> {
    await this.initialize();
    return this.colleges.find(college => college.id === id);
  }

  // 添加学院
  async addCollege(collegeData: Omit<College, 'id' | 'createdAt' | 'updatedAt'>): Promise<College> {
    await this.initialize();
    
    const newCollege: College = {
      ...collegeData,
      id: Date.now(),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    this.colleges.push(newCollege);
    this.saveToStorage();
    
    return newCollege;
  }

  // 更新学院
  async updateCollege(id: number, collegeData: Partial<College>): Promise<College | undefined> {
    await this.initialize();
    
    const index = this.colleges.findIndex(college => college.id === id);
    if (index === -1) {
      return undefined;
    }
    
    this.colleges[index] = {
      ...this.colleges[index],
      ...collegeData,
      updatedAt: new Date().toISOString(),
    };
    
    this.saveToStorage();
    return this.colleges[index];
  }

  // 删除学院
  async deleteCollege(id: number): Promise<boolean> {
    await this.initialize();
    
    const index = this.colleges.findIndex(college => college.id === id);
    if (index === -1) {
      return false;
    }
    
    this.colleges.splice(index, 1);
    this.saveToStorage();
    
    return true;
  }

  // 搜索学院
  async searchColleges(query: string): Promise<College[]> {
    await this.initialize();
    
    if (!query.trim()) {
      return [...this.colleges];
    }
    
    const lowerQuery = query.toLowerCase();
    return this.colleges.filter(college => 
      college.name.toLowerCase().includes(lowerQuery) ||
      college.dean.toLowerCase().includes(lowerQuery) ||
      college.location.toLowerCase().includes(lowerQuery)
    );
  }
}

// 创建单例实例
export const collegeService = new CollegeService();